<template>
  <el-popover
    v-model="show"
    popper-class="no-padding-popover"
    placement="bottom-end"
    width="240"
    trigger="click"
    class="field-set-wrap">
    <div class="field-set">
      <el-input
        v-model="search"
        class="field-set__search"
        :placeholder="$t('crm.components.0c7e143f24c394addf0781209f56b333')"
        @input="searchClick" />

      <div class="field-set__title">{{ $t('crm.components.f3bc3f14e27e4201e7b94a2ff746b5fc') }}</div>
      <div
        ref="fieldContent"
        v-loading="loading"
        class="field-set__content"
        :style="{'max-height': listMaxHeight + 'px'}">
        <flexbox
          v-for="(item, index) in disabledFields"
          v-show="(poolConfig != 1 && item.fieldName !== 'poolDay') || poolConfig == 1"
          :key="index"
          class="field-set__content--item ">
          <el-checkbox v-model="item.check">
            <span v-if="item.center">
              {{ item.left }}
              <span class="input-word">{{ item.center }}</span>
              {{ item.right }}
            </span>
            <span v-else>{{ item.name }}</span>
          </el-checkbox>
          <div class="hover-btn">
            <span>已锁定</span>
          </div>
        </flexbox>
        <draggable
          v-model="dragFields"
          :options="{
            filter: '.el-checkbox',
            handle: '.drag-handle'
          }">
          <flexbox
            v-for="(item, index) in dragFields"
            v-show="(poolConfig != 1 && item.fieldName !== 'poolDay') || poolConfig == 1"
            :key="index"
            class="field-set__content--item ">
            <el-checkbox v-model="item.check">
              <span v-if="item.center">
                {{ item.left }}
                <span class="input-word">{{ item.center }}</span>
                {{ item.right }}
              </span>
              <span v-else>{{ item.name }}</span>
            </el-checkbox>
            <div class="hover-btn">
              <span style="color: #0052cc;cursor: pointer;" @click.stop="handleTop(index)">置顶</span>
              <span class="drag-handle">⋮⋮</span>
            </div>
          </flexbox>
        </draggable>
      </div>

      <div class="field-set__ft">
        <div v-if="showSyncAllEmployees" class="ft-item is-switch">
          <el-switch
            v-model="syncAllEmployees" /><span>是否同步全体员工</span>
        </div>
        <div class="ft-item">
          <el-button type="primary" size="medium" @click="save">{{ $t('crm.components.0d15cc750818367fa77c2649ef423a3f') }}</el-button>
          <el-button size="medium" type="text" @click="reSet">{{ $t('crm.components.51d26b9d6cfb3f589b93c807325a4af9') }}</el-button>
        </div>
      </div>
    </div>
    <slot v-if="$slots.reference" slot="reference" @click="show = !show" />
    <el-button
      v-else
      slot="reference"
      :type="show ? 'selected' : ''"
      icon="wk wk-icon-config-line"
      class="set-btn"
      @click="show = !show" />
  </el-popover>
</template>

<script>
import {
  crmFieldConfigAPIIndexAPI,
  crmPoolFieldConfigIndexAPI,
  crmFieldConfigAPI
} from '@/api/crm/common'
import {
  crmLeadsPoolFieldConfigIndexAPI,
  crmLeadsPoolFieldConfigAPI
} from '@/api/crm/leads'

import {
  crmCustomerPoolFieldConfigAPI
} from '@/api/crm/customer'

import crmTypeModel from '@/views/crm/model/crmTypeModel'

import Draggable from 'vuedraggable'

import { objDeepCopy } from '@/utils'
import { mapGetters } from 'vuex'

export default {
  /** 字段管理 */
  name: 'FieldSet',
  components: {
    Draggable
  },
  props: {
    crmType: String,

    isSeas: {
      type: Boolean,
      default: false
    },

    poolId: [String, Number]
  },
  data() {
    return {
      loading: false,
      show: false,
      poolConfig: 1, // 1 公海规则打开  0 未打开
      fields: [],
      disabledFields: [],
      dragFields: [],
      // 用于重置
      copyfields: [],
      search: '',
      // 是否同步全体员工
      syncAllEmployees: false,

      listMaxHeight: ''
    }
  },
  computed: {
    ...mapGetters([
      'userInfo'
    ]),
    // 是否展示同步，仅管理员和非公海下展示
    showSyncAllEmployees() {
      return this.userInfo?.isAdmin && !this.isSeas
    }
    // showFields() {
    //   if (this.search) {
    //     return this.fields.filter(item => {
    //       return item.name.indexOf(this.search) != -1
    //     })
    //   }
    //   return this.fields
    // }
  },
  watch: {
    show(val) {
      if (val) {
        this.getList()
      }
    },

    poolId() {
      this.fields = []
      if (this.show) {
        this.getList()
      }
    }
  },
  mounted() {},

  beforeDestroy() {},
  methods: {
    /**
     * 获取数据
     */
    getList() {
      this.loading = this.fields.length == 0
      let request = null
      const params = {}
      if (this.isSeas) {
        request = {
          customer: crmPoolFieldConfigIndexAPI,
          leads: crmLeadsPoolFieldConfigIndexAPI
        }[this.crmType]
        params.poolId = this.poolId
      } else {
        request = crmFieldConfigAPIIndexAPI
        params.label = crmTypeModel[this.crmType]
      }

      request(params)
        .then(res => {
          const resData = res.data || {}
          this.poolConfig = resData.poolConfig
          const showList = (resData.value || []).map(item => {
            item.left = ''
            item.center = ''
            item.right = ''
            item.check = true
            return item
          })
          const hideList = (resData.hideValue || []).map(item => {
            item.left = ''
            item.center = ''
            item.right = ''
            item.check = false
            return item
          })
          this.fields = showList.concat(hideList)
          this.getShowFields(this.fields)
          this.copyfields = objDeepCopy(this.fields)
          this.loading = false

          this.$nextTick(() => {
            this.listMaxHeight = this.$parent.$parent.maxTableHeight - 202
          })
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * 获取展示数组
     */
    getShowFields(list) {
      let isDrag = false
      const disabledFields = []
      const dragFields = []
      list.forEach(item => {
        if (item.isLock !== 1) {
          isDrag = true
        }
        if (isDrag) {
          dragFields.push(item)
        } else {
          disabledFields.push(item)
        }
      })

      this.dragFields = dragFields
      this.disabledFields = disabledFields
    },

    /**
     * 搜索操作
     */
    searchClick() {
      let matchIndex = -1 // 记录第一个匹配的位置
      this.fields = this.fields.map((item, itemIndex) => {
        const index = item.name.indexOf(this.search)
        if (index != -1) {
          if (matchIndex === -1) matchIndex = itemIndex
          item.left = item.name.substr(0, index)
          item.center = item.name.substr(index, this.search.length)
          const rightIndex = index + this.search.length
          item.right = item.name.substr(rightIndex, item.name.length - rightIndex)
        } else {
          item.left = ''
          item.center = ''
          item.right = ''
        }
        return item
      })

      if (matchIndex !== -1) {
        this.$refs.fieldContent.scrollTop = matchIndex * 34 // 34行高
      }
    },

    /**
     * 保存更改
     */
    save() {
      const allFields = this.disabledFields.concat(this.dragFields)
      const noHideFields = allFields.filter(item => item.check)
      if (noHideFields.length < 2) {
        this.$message.error(this.$t('crm.components.6575a09fa1baea2fafa1ceef2abd5c95'))
      } else {
        const hideFields = allFields.filter(item => !item.check)
        this.loading = true
        let request = null
        const params = {
          noHideFields: noHideFields
            .map(item => {
              return {
                id: item.id,
                fieldName: item.fieldName,
                style: item.style
              }
            }),
          hideFields: hideFields
            .map(item => {
              return {
                id: item.id,
                fieldName: item.fieldName,
                style: item.style
              }
            }) }
        if (this.isSeas) {
          request = {
            leads: crmLeadsPoolFieldConfigAPI,
            customer: crmCustomerPoolFieldConfigAPI
          }[this.crmType]
          params.poolId = this.poolId
        } else {
          request = crmFieldConfigAPI
          params.label = crmTypeModel[this.crmType]
        }

        if (this.showSyncAllEmployees) {
          params.resetCompanyFieldSort = this.syncAllEmployees
        }

        request(params)
          .then(res => {
            this.$message.success(this.$t('crm.components.3544d13a4239eef32cffa297dd50908c'))
            this.show = false
            this.loading = false
            this.$emit('change')
          })
          .catch(() => {
            this.loading = false
          })
      }
    },

    /**
     * 重置
     */
    reSet() {
      this.fields = objDeepCopy(this.copyfields)
      this.getShowFields(this.fields)
    },

    /**
     * @description: 置顶
     * @param {*} item
     * @return {*}
     */
    handleTop(index) {
      const deleteItem = this.dragFields.splice(index, 1)
      this.dragFields.splice(0, 0, deleteItem[0])
    }
  }
}
</script>

<style lang="scss" scoped>
.field-set {
  &__search {
    padding: 8px 10px 0;
  }

  &__title {
    padding: 15px 15px 0;
    font-size: 12px;
    color: $--color-n200;
  }

  &__content {
    min-height: 100px;
    max-height: 250px;
    overflow: auto;

    &--item {
      display: flex;
      justify-content: space-between;
      padding: 0 15px;
      line-height: 34px;

      .el-checkbox {
        width: calc(100% - 50px);

        ::v-deep .el-checkbox__label {
          width: calc(100% - 15px);
        }
      }

      .hover-btn {
        display: none;
        justify-content: flex-start;

        .drag-handle {
          display: none;
          flex-shrink: 0;
          margin-left: 8px;
          font-weight: bold;
          cursor: move;
        }
      }
    }

    &--item:hover {
      background-color: $--color-b50;

      .hover-btn {
        display: flex;

        .drag-handle {
          display: inline-block;
        }
      }
    }
  }

  &__ft {
    padding: 8px;
    overflow: hidden;
    overflow-y: overlay;
    font-size: 0;
    text-align: right;

    .ft-item {
      &.is-switch {
        font-size: 14px;
        text-align: left;

        span {
          margin-left: 8px;
          color: $--color-text-secondary;
        }
      }
    }

    .ft-item + .ft-item {
      margin-top: 8px;
    }
  }
}

.set-btn {
  padding: 11px 8px;
  font-size: 16px;
}

// 搜索到的字
.input-word {
  color: white;
  background-color: $--color-primary;
}

// ::v-deep .el-checkbox {
//   .el-checkbox__input.is-checked {
//     .el-checkbox__inner {
//       background-color: $--color-b300;
//       border-color: $--color-b300;
//     }
//   }
// }
</style>
